/**
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company: 联动优势电子商务有限公司</p>
 * <p>16-11-14</p>
 *
 * @author xtdhwl
 * @description
 * @version 1.0
 * modified:
 */




/**
 *  字符串工具类
 */
export default class StringUtils {

    /**
     * base64解码
     * @param str
     * @returns {string}
     */
    base64Decode(str) {
        return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
    }

    /**
     * base64编码
     * @param str
     * @returns {string}
     */
    base64Encode(str) {
        return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
            return String.fromCharCode('0x' + p1);
        }));
    }

    static hexToString(c){
        var b = "";
        for (var a = 0; a < c.length - 1; a += 2) {
            b += String.fromCharCode(parseInt(c.substr(a, 2), 16))
        }
        return b
    }

    /**
     * 字符转16进制
     * @param str
     * @returns {string}
     */
    static stringToHex(str) {
        var bytes = StringUtils.stringToBytes(str);

        var result = '';
        for(var i = 0; i< bytes.length; i++){
           // result += bytes[i].toString(16);
            result = result.concat(bytes[i].toString(16));
        }
        return result;
    }

    /**
     * 字符转字节
     * @param str
     * @returns {Array}
     */
    static stringToBytes(str){
        var bytes = [];
        for (var i = 0; i < str.length; ++i) {
            bytes.push(str.charCodeAt(i));
        }
        return bytes;
    }


    static safeTrim(str) {
        if (str) {
            return str.trim();
        }
        return "";
    }

    static safeTrimObj(obj) {
        if (obj) {
            for (let key of Object.keys(obj)) {
                let value = obj[key];
                if (value && typeof value === 'string') {
                    obj[key] = value.trim();
                }
            }
        }
        return obj;
    }
}